<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2019/6/5
 * Time: 17:07
 */

namespace Hilaoyu\Utils\Drivers\Sms;


use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilRegex;
use PHPUnit\Util\Type;

class Juhe
{
    use ErrorsTrait;
    protected $config = [];
    protected const API_URL = 'http://v.juhe.cn/sms/send';

    public function __construct($config=[])
    {

        $this->setConfig($config);
    }

    public function setConfig($config=[]){
        $this->config = (array)$config;
    }

    public function getConfig($key=''){
        $key = trim($key);

        if($key){
            return UtilArr::get($this->config,$key);
        }

        return $this->config;
    }

    protected function buildTplValue($content){
        $content = (array)$content;
        $str_value =  UtilArr::toString($content,'&',true,'=');

        return urlencode($str_value);
    }

    public function send($phone,  $content,$tpl = '') {
        $phone = trim($phone);
        $tpl = trim($tpl);

        if(!UtilRegex::isMobile($phone)){
            $this->setError('手机号格式错误');
            return false;
        }


        $smsConf = array(
            'key' => $this->getConfig('app_key'), //您申请的APPKEY
            'mobile' => $phone, //接受短信的用户手机号码
            'tpl_id' => $tpl, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => $this->buildTplValue($content) //您设置的模板变量，根据实际情况修改
        );

        //dd(static::API_URL,$smsConf);
        $result = UtilHttp::RequestJson(static::API_URL,$smsConf,'post'); //请求发送短信
        if ($result) {
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                //状态为0，说明短信发送成功
                //echo "短信发送成功,短信ID：" . $result['result']['sid'];
                return TRUE;
            } else {
                //状态非0，说明失败
                $msg = $result['reason'];
                $this->setError("短信发送失败(" . $error_code . ")：" . $msg);

                return FALSE;
            }
        } else {
            //返回内容异常，以下可根据业务逻辑自行修改
            $this->setError(UtilHttp::getStaticError());
            return FALSE;
        }
    }
}
